from django import template
from django.template import TemplateSyntaxError, Library
from django.utils import translation
from django.conf import settings

register = Library()

class GetLanguageNameNode(template.Node):
    def __init__(self, lang, var):
        self.lang = template.Variable(lang)
        self.variable = var

    def render(self, context):
        lang = self.lang.resolve(context)
        for l in settings.LANGUAGES:
            if lang == l[0]:
                if self.variable:
                    context[self.variable] = l[1]
                    return ''
                else:
                    return l[1]


def do_get_language_name(parser, token):
    args = token.contents.split()
    var = None
    lang = None
    if len(args) == 4 and args[2] == 'as':
        var = args[3]
        lang = args[1]
    elif len(args) == 2:
        lang = args[1]
        
    return GetLanguageNameNode(lang, var)

register.tag('language_name', do_get_language_name)

